package configs

import (
	"git.huoys.com/block_chain/mall/pkg/database/mysql"
	"git.huoys.com/block_chain/mall/pkg/database/redis"
	"git.huoys.com/block_chain/mall/pkg/log"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
)

const (
	CreateUserDefaultComputingPower float32 = 50 // 注册送50算力
)

var BlockchainAddr string

type Config struct {
	Development bool
	GinServer   ginConf
}

type ginConf struct {
	Name         string // 服务名称
	ServerAddr   string // 服务地址
	RunMode      string // 运行模式
	ReadTimeout  int    // 单位s
	WriteTimeout int    // 单位s
}

func NewViper() (*viper.Viper, error) {
	v := viper.New()
	v.AddConfigPath("./cmd")
	//v.AddConfigPath("./")
	v.SetConfigName("application")
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		return nil, errors.Wrap(err, "read configs")
	}
	BlockchainAddr = v.GetString("blockchainAddr")
	if BlockchainAddr == "" {
		return nil, errors.New("BlockchainAddr err")
	}
	return v, nil
}

func NewTestViper(path string) (*viper.Viper, error) {
	v := viper.New()
	v.AddConfigPath(path)
	v.SetConfigName("application")
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		return nil, errors.Wrap(err, "read configs")
	}
	BlockchainAddr = v.GetString("blockchainAddr")
	if BlockchainAddr == "" {
		return nil, errors.New("BlockchainAddr err")
	}
	return v, nil
}

func NewServerConfig(v *viper.Viper) (conf Config, err error) {
	conf.Development = v.GetBool("development")
	if err = v.UnmarshalKey("ginServer", &conf.GinServer); err != nil {
		err = errors.Wrap(err, "unmarshal GinConfig error")
	}
	return
}

func NewLoggerCfg(v *viper.Viper) (conf *log.Options, err error) {
	conf = new(log.Options)
	if err = v.UnmarshalKey("log", conf); err != nil {
		err = errors.Wrap(err, "unmarshal log error")
	}
	return
}

func NewMysqlConfig(v *viper.Viper) (conf *mysql.Config, err error) {
	conf = new(mysql.Config)
	if err = v.UnmarshalKey("mysql", &conf); err != nil {
		err = errors.Wrap(err, "unmarshal NewMysqlConfig error")
	}
	return
}

func NewRedisConfig(v *viper.Viper) (conf redis.Config, err error) {
	if err = v.UnmarshalKey("redis", &conf); err != nil {
		err = errors.Wrap(err, "unmarshal NewRedisConfig error")
	}
	return
}
